const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')

const handleBlogRouter = (req, res) => {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]

    // 获取博客列表
    if (method === "GET" && path === '/api/blog/list') {
        const author = req.query.author || '';
        const keyword = req.query.keyword || '';
        // const listData = getList(author, keyword)
        const result = getList(author, keyword)
        return result.then(listData => {
            return new SuccessModel(listData)
        })

    }
    // 获取博客详情
    if (method === "GET" && path === '/api/blog/detail') {
        const id = req.query.id
        // const data = getDetail(id)
        // return new SuccessModel(data)

        const result = getDetail(id)
        return result.then(data => {
            return new SuccessModel(data)
        })
    }
    // 新建博客
    if (method === "POST" && path === '/api/blog/new') {
        const data = newBlog(req.body)
        return new SuccessModel(data)
    }
    // 更新博客
    if (method === "POST" && path === '/api/blog/update') {
        const data = updateBlog(req.query.id, req.body)
        if (data) {
            return new SuccessModel()
        } else {
            return new ErrorModel('err')
        }
    }
    // 删除博客
    if (method === "POST" && path === '/api/blog/del') {
        const data = delBlog(req.query.id)
        if (data) {
            return new SuccessModel()
        } else {
            return new ErrorModel('err')
        }
    }
}

module.exports = handleBlogRouter